<template>
  <div class="police-bssic-infor">
    <CustomSearch ref="searchRef" v-model:form="form" :showRest="false" @search="getData">
      <template #moreHandle>
        <el-button type="primary" @click="asyncData">重新同步</el-button>
      </template>
    </CustomSearch>
    <el-card body-class="list-card" v-loading="loading" style="margin-top: 10rem">
      <div class="status" :style="{ color: status == 'querying' ? '#409eff' : status == 'finish' ? '#67C23A' : 'red' }">{{ statusTitle }}</div>
      <el-scrollbar v-if="tableData.length > 0" height="845rem">
        <table v-for="(item, index) in tableData" :key="item.rybh" border>
          <tr>
            <th class="index" width="80px">序号</th>
            <th class="origin">数据来源</th>
            <th class="name">姓名</th>
            <th class="photo">照片</th>
            <th class="card-number">卡号</th>
            <th class="idcard">身份证号</th>
            <th>密码</th>
          </tr>
          <tr>
            <th rowspan="2" class="index">{{ index + 1 }}</th>
            <td class="origin">数据库</td>
            <td class="name">{{ item.mjmz }}</td>
            <td class="photo">
              <el-popover v-if="item.zpurl" placement="right" :width="200" trigger="click" content="">
                <img :src="item.zpurl" style="width: 100%" />
                <template #reference>
                  <img v-if="item.zpurl" class="avatar" :src="item.zpurl" />
                </template>
              </el-popover>
            </td>
            <td class="card-number">{{ item.kh }}</td>
            <td class="idcard">{{ item.sfzh }}</td>
            <td>{{ item.password }}</td>
          </tr>
          <tr>
            <td class="origin">终端</td>
            <td class="name">{{ searchByRybh(item).mjmz }}</td>
            <td class="photo">
              <el-popover v-if="searchByRybh(item).zpurl" placement="right" :width="200" trigger="click" content="">
                <img :src="item.zpurl" style="width: 100%" />
                <template #reference>
                  <img v-if="searchByRybh(item).zpurl" class="avatar" :src="searchByRybh(item).zpurl" />
                </template>
              </el-popover>
            </td>
            <td class="card-number">{{ searchByRybh(item).kh }}</td>
            <td class="idcard">{{ searchByRybh(item).sfzh }}</td>
            <td>{{ searchByRybh(item).password }}</td>
          </tr>
        </table>
      </el-scrollbar>
      <custom-empty v-else height="845rem"></custom-empty>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onBeforeMount, onMounted, computed, watch, onBeforeUnmount, reactive } from 'vue'
import { Search, Refresh } from '@element-plus/icons-vue'
import { http } from '@/utils/index.js'
import { stores } from '@/stores/index.js'
import Stomp from 'stompjs'
let sokect = null
let stompClient = null
let timer = null //websoket  断开重连定时器
let wsData = {} //websoket地址信息
const useInfor = stores.useUserStore()
const props = defineProps({})
const loading = ref(false)
const status = ref('noSignal') //终端推送数据状态
const tableData = ref([]) //数据库查询到数据
const personData = ref([]) // websoket 推送的数据
const form = ref({
  JSH: '0101'
})

const statusTitle = computed(() => {
  return status.value == 'noSignal' ? '未查询到监室终端数据' : status.value == 'finish' ? '监室终端数据查询成功' : '正在查询监室终端数据..'
})
onMounted(async () => {
  getJsh()
  getWsUrl()
})
onBeforeUnmount(() => {
  if (sokect) {
    sokect.close()
  }
  clearTimeout(timer)
})
//获取websockt 地址
const getWsUrl = () => {
  http('/znjszd3/ht/cnpDataVerify/getWsForCnpDataVerify', 'get', {
    type: 'mjxx'
  }).then((res) => {
    wsData = res.data
    connectStomp()
  })
}
const connectStomp = () => {
  clearTimeout(timer)
  if (stompClient !== null) {
    stompClient.disconnect()
  }
  const ws = new WebSocket(wsData.wsUrl)
  stompClient = Stomp.over(ws)
  // stompClient.heartbeat.outgoing = 60000
  // stompClient.heartbeat.incoming = 60000
  stompClient.debug = () => {}
  stompClient.connect(
    { username: '' },
    () => {
      stompClient.subscribe(wsData.wsDestination, function (message) {
        const msg = JSON.parse(message.body)
        console.log(msg)
        if (msg.doWhat !== 'getMjxxListFromCnping') {
          status.value = 'querying'
        }
        if (msg.doWhat == 'getMjxxListFromCnpFinish') {
          personData.value = msg.data || []
          status.value = 'finish'
        }
      })
    },
    () => {
      console.log('stomp断开了')
      timer = setTimeout(() => {
        connectStomp()
      }, 2000)
    }
  )
}
const getJsh = () => {
  http('/znjszd3/comm/getJshsByDwdm', 'get', {
    type: 'tree'
  }).then(async (res) => {
    const jsh = res.data[0].children[0].zddm
    form.value.JSH = jsh
    getData({ JSH: jsh })
    // initWebsockt()
  })
}
const getData = (params) => {
  loading.value = true
  status.value = 'noSignal'
  http('/znjszd3/ht/cnpDataVerify/getMjxxByDwdm', 'get', {
    jsh: params.JSH
  })
    .then((res) => {
      tableData.value = res.data
      personData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}

//通过人员编号查询对应的终端数据
const searchByRybh = (person) => {
  const obj = personData.value.find((item) => item.id == person.id)
  if (obj) {
    return obj
  } else {
    return {}
  }
}

const asyncData = () => {
  ElMessageBox.confirm(`是否立即通知 ${form.value.JSH}监室终端重新同步数据?`, '', {
    confirmButtonText: '是',
    cancelButtonText: '否',
    type: 'infor'
  })
    .then(() => {
      loading.value = true
      http('/znjszd3/ht/cnpDataVerify/telCnpUpdateRyxxMjxx', 'get', {
        jsh: form.value.JSH
      })
        .then((res) => {
          console.log(res)
          if (res.status == 200) {
            ElMessage.success(res.message.join())
          }
        })
        .finally(() => {
          loading.value = false
        })
    })
    .catch(() => {})
}
</script>
<style lang="scss" scoped>
.police-bssic-infor {
}
.status {
  margin-bottom: 5px;
  font-size: 16px;
}
::v-deep(.list-card) {
  padding: 10px 20px !important;
}
::v-deep(.search.el-card) {
  margin-bottom: 8px;

  .el-form-item {
    margin-bottom: 0;
  }
}
table {
  margin-bottom: 15px;
  width: 100%;
  border-collapse: collapse;
  border-radius: 10px;

  th.index,
  td.index {
    width: 3%;
  }
  .origin,
  .name,
  .photo,
  .card-number {
    width: 13%;
  }
  .idcard {
    width: 20%;
  }

  th {
    height: 50px;
    text-align: center;
  }

  td {
    height: 70px;
    text-align: center;
    img {
      display: inline-block;
      height: 90%;
      border: none;
    }
  }
  td.photo {
    padding-top: 3px;
  }

  .finger,
  .avatar {
    margin-top: 3px;
    cursor: pointer;
  }
}
</style>
